//
// Created by v on 24-5-13.
//

#include <string.h>
#include <unistd.h>

#include "cm_broadcast_function.h"
#include "utils/rt_print.h"

CMBroadcastFunction::CMBroadcastFunction() : CMTimeout(5)
{
}

CMBroadcastFunction::~CMBroadcastFunction() {}

int CMBroadcastFunction::start(int port, bool recv) {
    name = std::to_string(port);
    name += " - ";
    name += std::to_string(recv);
    int ret = cm_broadcast_init(&broadcastHandle, port);
    if (ret < 0)
    {
        rterror("broadcast init failed ret [%d]", ret);
        return -2;
    }
    ret = cm_broadcast_socket_init_simple(broadcastHandle);
    rtinfo("broadcast init of port [%d] success ret=[%d]", port, ret);
    if (recv)
    {
        ret = cm_broadcast_bind(broadcastHandle);
        rtinfo("broadcast bind ret = [%d]", ret);
    }
    CMTimeout::start();
    return ret;
}

int CMBroadcastFunction::stop() {
    rtdebug("stop");
    cm_broadcast_close(&broadcastHandle);
    return 0;
}

int CMBroadcastFunction::sendBroadcast(std::string &data) {
    static int count = 0;
    if (check() > 0)
    {
        cm_broadcast_send(broadcastHandle, (char*)data.c_str(), data.length());
        rtdebug("send broadcast count [%d]", count++);
    }
    return 0;
}

int CMBroadcastFunction::recvBroadcast(std::string &data) {
    char res[1024] = {0};
    size_t len = sizeof(res);
    int ret = -1;
    int c = 0;
    int max_count = 1000/50;
    while (c < max_count)
    {
        ret = cm_broadcast_recv(broadcastHandle, res, len);
        if (ret < 0)
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                usleep(50000);
                c++;
                continue;
            }
            else
            {
                rtdebug("recv data result ret [%d][%d][%s]", ret, errno,
                        strerror(errno));
                break;
            }
        }
        data = res;
        break;
    }
    return ret;
}
